<template>
  <div class="app-container">
    <div class="flex-box">
      <div class="item">
        <el-button @click="addShow">添加场景</el-button>
      </div>

      <div class="item">
        <el-select v-model="searchtype" placeholder="请选择场景类型" @change="getList">
          <el-option
            :key="0"
            label="全部场景类型"
            :value="null"
          />
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="item">
        <el-input v-model="searchcontent" placeholder="请输入场景标题英文名">
          <el-button slot="append" icon="el-icon-search" @click="getList">搜索</el-button>
        </el-input>
      </div>
      <div class="item">
        <span>总共有{{ total }}条数据</span>
      </div>
    </div>

    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row class="no-r-b"
      :header-cell-style="{background:'#FAFAFA',color:'#666666'}">
      <el-table-column align="center" show-overflow-tooltip label="ID">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="场景英文标题" >
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="场景中文标题">
        <template slot-scope="scope">
          <span>{{ scope.row.title_zn }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="场景主图">
        <template slot-scope="scope">
          <el-image :src="domainName+scope.row.image"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="场景价格">
        <template slot-scope="scope">
          <span>{{ scope.row.price/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="场景类型">
        <template slot-scope="scope">
          <span>{{ scope.row.type == 1 ? '生日场景' : '纪念日场景' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="所属桌子">
        <template slot-scope="scope">
          <span>{{ scope.row.tablenames }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="70">
        <template slot-scope="scope">
          <div style="color: #1890FF;cursor: pointer;">
            <span type="primary" size="small" icon="el-icon-edit" @click="editShow(scope.row)">编辑</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-if="total>0" :total="total" :page.sync="listParams.page" :limit.sync="listParams.limit" @pagination="getList" />

    <!--列表数据添加/编辑开始  -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" center width="95%" class="sen">
      <el-form ref="ruleForm" :model="fromParams" label-width="90px">
        <el-form-item label="场景主图">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="doUploadImg"
            :show-file-list="false"
          >
            <img v-if="fromParams.image" style="width: 100%;" :src="domainName+(fromParams.image)" class="avatar">
            <img v-else src="../../../public/img/prod_img.png" />
          </el-upload>
        </el-form-item>
        <el-form-item label="场景英文名">
          <el-input v-model="fromParams.title" auto-complete="off" />
        </el-form-item>
        <el-form-item label="场景中文名">
          <el-input v-model="fromParams.title_zn" auto-complete="off" />
        </el-form-item>
        <el-form-item label="场景价格">
          <el-input type="number" v-model="fromParams.price" auto-complete="off" />
        </el-form-item>
        <el-form-item label="场景类型">
          <div style="line-height: 36px;">
            <el-radio v-model="fromParams.type" :label="1">生日场景</el-radio>
            <el-radio v-model="fromParams.type" :label="2">纪念日场景</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="所属桌子">
          <div class="dinList">
            <el-table ref="multipleTable" v-loading="dinlistLoading" :data="dinlist" border fit highlight-current-row style="width: 100%" class="no-r-b"
              :header-cell-style="{background:'#FAFAFA',color:'#666666'}">
              <el-table-column align="center" width="50">
                <template slot="header">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="selectAllStatus" @change="selectAll"></el-checkbox>
                </template>
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.select" @change="selectSingle($event,scope.$index)"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column align="center" show-overflow-tooltip label="餐桌名称">
                <template slot-scope="scope">
                  <span>{{ scope.row.title_zn + '('+ scope.row.title +')' }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column align="center" show-overflow-tooltip label="餐桌图片" >
                <template slot-scope="scope">
                  <el-image style="width: 100px;" :src="domainName+scope.row.image"></el-image>
                </template>
              </el-table-column> -->
            </el-table>
            <pagination :total="dinTotal" :page.sync="dinlistParams.page" :pageSizes="[5,10,15,20]" :layout="'sizes, prev, pager, next'" :limit.sync="dinlistParams.limit" @pagination="getDinList" />
          </div>
        </el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form>
    </el-dialog>
    <!--列表数据添加/编辑结束  -->
  </div>
</template>

<script>
import { getSenList, addSen, editSen, getDinList } from '@/api/din'
import { uploadImg } from '@/api/uploadImg'
import Pagination from '@/components/Pagination'
import imgzip from 'imgzip'
export default {
  name: 'SenList',
  components: { Pagination },
  data() {
    return {
      list: [],
      listParams:{
       page: 1,
       limit: 10
      },
      fromParams:{
        title: '',
        title_zn: '',
        image: '',
        price: 0,
        type: '',
        tids: ''
      },
      searchtype: '', // 搜索场景类型
      searchcontent: '', // 搜索场景标题英文名
      listLoading: '',
      total: 0,
      dialogTitle: '',
      dialogFormVisible: false,
      dinlist:[],
      dinlistLoading: false,
      dinlistParams:{
        page: 1,
        limit: 5
      },
      dinTotal: 0,
      domainName: process.env.VUE_APP_BASE_DOMAIN,
      multipleSelection: [],//被选中的桌子
      selectTids: [],
      typeList: [
        {value: 1,label: '生日场景'},
        {value: 2,label: '纪念日场景'}
      ],
      isIndeterminate: false,
      selectAllStatus: false,
      selectedSum: 0
    }
  },
  created() {
    this.getList()
  },
  methods:{
    getList() {
      this.listLoading = true
      const search = { searchcontent: this.searchcontent, searchtype: this.searchtype }
      const postdata = { ...this.listParams, ...search }
      getSenList(postdata).then((response) => {
        const { data } = response
        console.log(response, 'getSenList')
        this.list = data.list
        this.total = data.total
        this.listLoading = false
      })
    },
    selectAll(e) {
      this.dinlist.forEach(item=>{
        this.isIndeterminate = false
        item.select = e
        if(e){
          this.selectedSum++
          this.multipleSelection.push(item)
        }else{
          this.selectedSum--
          // let chuzai = this.multipleSelection.indexOf(item) !== -1
          // console.log(chuzai)
          // if(chuzai) {
            let tid = (item.id).toString()
            this.multipleSelection = this.multipleSelection.filter((item) => {
              return !tid.includes(item.id)
            });
          // }
        }
      })
      if(this.multipleSelection.length>0){
        let ids=[];
        this.multipleSelection.forEach(item=>{
          ids.push(item.id)
        })
        ids=ids.join(',')
        this.fromParams.tids = ids
        this.selectTids = this.fromParams.tids.split(',')
      }else{
        this.fromParams.tids = ''
        this.selectTids = []
      }
    },
    selectSingle(e,index) {
      console.log(e)
      if(e){
        this.multipleSelection.push(this.dinlist[index])
        this.selectedSum++
      }else{
        this.selectedSum--
        // let chuzai = this.multipleSelection.indexOf(this.dinlist[index]) !== -1
        // console.log(chuzai)
        // if(chuzai) {
        let tid = (this.dinlist[index].id).toString()
        this.multipleSelection = this.multipleSelection.filter((item) => {
          return !tid.includes(item.id)
        });
        // }
      }
      console.log(this.selectedSum)
      this.isIndeterminate = this.selectedSum>0 && this.selectedSum != this.dinlist.length
      this.selectAllStatus = this.selectedSum>0 && this.selectedSum == this.dinlist.length
      if(this.multipleSelection.length>0){
        let ids=[];
        this.multipleSelection.forEach(item=>{
          ids.push(item.id)
        })
        ids = Array.from(new Set(ids))
        ids = ids.join(',')
        this.fromParams.tids = ids
        this.selectTids = this.fromParams.tids.split(',')
      }else{
        this.fromParams.tids = ''
        this.selectTids = []
      }
    },
    getDinList(){
      this.dinlistLoading = true;
      getDinList(this.dinlistParams).then(res=>{
        res.data.list.forEach(item=>{
          item.select = false
        })
        this.dinlist = res.data.list
        this.dinTotal = res.data.total
        this.dinlistLoading = false
      }).then(()=>{
        this.selectedSum = 0
        if(this.selectTids.length>0){
          for(let i=0;i<this.selectTids.length;i++){
            for(let j=0;j<this.dinlist.length;j++){
              if(this.dinlist[j].id == this.selectTids[i]){
                this.selectedSum++
              }
            }
          }
          this.isIndeterminate = this.selectedSum>0 && this.selectedSum != this.dinlist.length
          this.selectAllStatus = this.selectedSum>0 && this.selectedSum == this.dinlist.length
          for(let i=0;i<this.selectTids.length;i++){
            for(let j=0;j<this.dinlist.length;j++){
              if(this.dinlist[j].id == this.selectTids[i]){
                this.dinlist[j].select = true
              }
            }
          }
        }
      })
    },
    //添加
    addShow() {
      this.fromParams = {
        title: '',
        title_zn: '',
        image: '',
        price: 0,
        type: '',
        tids: ''
      }
      this.dinlistParams = {
        page: 1,
        limit: 5
      }
      this.selectTids = []
      this.dialogFormVisible = true
      this.dialogTitle = '添加场景'
      this.getDinList()
    },
    //编辑
    editShow(row) {
      this.dinlistParams = {
        page: 1,
        limit: 5
      }
      this.fromParams = {
        id: row.id,
        title: row.title,
        title_zn: row.title_zn,
        image: row.image,
        price: row.price/100,
        type: row.type,
        tids: row.tids
      }
      this.selectTids = this.fromParams.tids.split(',')
      this.dialogFormVisible = true
      this.dialogTitle = '编辑场景'
      this.getDinList()
    },
    //提交表单
    submitForm() {
      let submitData = {
        id: this.fromParams.id,
        title: this.fromParams.title,
        title_zn: this.fromParams.title_zn,
        image: this.fromParams.image,
        price: this.fromParams.price*100,
        type: this.fromParams.type,
        tids: this.fromParams.tids
      }
      if (this.fromParams.id) {
        editSen(submitData).then(res => { // 编辑
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.getList()
          this.dialogFormVisible = false
        })
      } else {
        addSen(submitData).then(res => { // 添加
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2 * 1000
          })
          this.getList()
          this.dialogFormVisible = false
        })
      }
    },
    //图片上传
    doUploadImg(params) {
      const compress = new imgzip({ quality: 0.8 })
      const _this = this
      // 调用图片压缩
      compress.photoCompress(params.file, function(base64) {
        const blob = imgzip.convertBase64UrlToBlob(base64)
        const formData = new FormData()
        formData.append('images', blob, 'file_' + Date.parse(new Date()) + '.jpg') // 文件对象
        // 上传操作....
        uploadImg(formData).then(response => {
          _this.fromParams.image = response.data
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(item=>{
        this.multipleSelection.push(item)
      })
      var newArr = [];
      this.multipleSelection.forEach((item) => {
        var check = newArr.every((b) => {
          return item.id !== b.id;
        })
        check ? newArr.push(item) : '';
      })
      this.multipleSelection = newArr;
      // if(this.multipleSelection.length>0){
      //   let ids=[];
      //   this.multipleSelection.forEach(item=>{
      //     ids.push(item.id)
      //   })
      //   ids=ids.join(',')
      //   this.fromParams.tids = ids
      //   this.selectTids = this.fromParams.tids.split(',')
      //   console.log(this.multipleSelection,this.selectTids,ids)
      // }else{
      //   this.fromParams.tids = ''
      //   this.selectTids = []
      // }
    },
    select(rows,row) {
      let selected = rows.length && rows.indexOf(row) !== -1
      if(selected) {
        rows.forEach(item=>{
          this.multipleSelection.push(item)
        })
        var newArr = [];
        this.multipleSelection.forEach((item) => {
          var check = newArr.every((b) => {
            return item.id !== b.id;
          })
          check ? newArr.push(item) : '';
        })
        this.multipleSelection = newArr;
      }else{

      }
    }
  }
}
</script>

<style>
</style>
